package cn.edu.lingnan.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
@WebFilter("/admin/*")

public class AuthorityFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //权限过滤器的作用：用户权限不同，页面不同
        //当管理员登录可以访问admin.jsp;当普通用户登录可以访问authority.html
        //把父类转子类
        HttpServletRequest req=(HttpServletRequest) servletRequest;
        HttpServletResponse resp=(HttpServletResponse) servletResponse;
        HttpSession session = req.getSession();
        Integer right=(Integer)session.getAttribute("right");
        System.out.println("[Debug 020] the student is right is " +right);
        //right有有一种可能 1 0 null
        if(right!=null){
            if(right==1){//管理员登录
                filterChain.doFilter(servletRequest,servletResponse);
            }else {
                resp.sendRedirect(req.getContextPath()+"/authority.html");
            }
        }else {//没有登录的情况
            resp.sendRedirect(req.getContextPath()+"/index.html");
        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
